import json
import os.path
from multiprocessing import Process

from flask import request

from httpserver.json_flask import JsonFlask
from httpserver.json_response import JsonResponse
from tess_local_simulator.main import start_local_tess_simulator

app = JsonFlask(__name__)
# 添加车辆数
platoon = 0
vehicleNum = 0
vehiclePoints = None
status = None

PENDING = 'pending'
SUCCESS = 'success'
ERROR = 'error'

process_car_dict = {}

process_dist = {}


@app.route('/startLocalSimulator', methods=['Post'])
def startLocalSimulator():
    '''
        启动仿真
    '''
    global process_dist
    # 获取仿真配置
    # sim_cfg = request.get_json()
    # assert 'type' in sim_cfg.keys(), '车辆行为不能为空，0-tess托管，3-逐帧映射'
    config_dict = {}
    # config_dict['netPath'] = r'D:\wn\cd_playoff\net_file\长安大学.tess'
    config_dict['netPath'] = r'D:\wn\cd_playoff\net_file\长安大学.tess'
    config_dict['proj'] = '+proj=tmerc +lon_0=108.90575652010739 +lat_0=34.37650478465651 +ellps=WGS84'
    # config_dict['type'] = sim_cfg['type']
    config_dict['target_topic'] = 'CA001MatchResultData'
    config_dict['radical_ratio'] = 0
    # 打开文件
    with open(r'D:\wn\cd_playoff\net_file\params.json', 'r') as file:
        data = json.loads(file.read())
        data = {int(k): v for k, v in data.items()}
        config_dict['scene_dict'] = data

    key = 'tess'
    if key in process_dist:
        return JsonResponse.success_with_msg('仿真程序已经在运行')
    tess_process = Process(target=start_local_tess_simulator, args=(config_dict,))
    tess_process.start()
    process_dist[key] = tess_process
    return JsonResponse.success_with_msg('仿真程序启动成功')


@app.route('/stopSimulator', methods=['Post'])
def stopSimulator():
    '''
        启动仿真
    '''
    global process_dist
    # 获取仿真配置
    sim_cfg = request.get_json()
    key = 'tess'
    if key not in process_dist.keys():
        return JsonResponse.success_with_msg('该测试任务未运行')
    task_process = process_dist.get(key)
    process_dist.pop(key)
    task_process.terminate()
    task_process.join()
    return JsonResponse.success_with_msg('仿真停止成功')


@app.errorhandler(Exception)
def error_handler(e):
    """
    全局异常捕获
    """
    return JsonResponse.error(msg=str(e))


def runstart():
    app.run(host='127.0.0.1', port=5002)


def httpserver():
    runstart()
